/*
 * Copyright 2012-present the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.security.oauth2.server.resource.autoconfigure.reactive;

import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.jspecify.annotations.Nullable;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.boot.security.oauth2.server.resource.autoconfigure.ConditionalOnIssuerLocationJwtDecoder;
import org.springframework.boot.security.oauth2.server.resource.autoconfigure.ConditionalOnPublicKeyJwtDecoder;
import org.springframework.boot.security.oauth2.server.resource.autoconfigure.OAuth2ResourceServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity.OAuth2ResourceServerSpec;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.jwt.JwtClaimValidator;
import org.springframework.security.oauth2.jwt.JwtIssuerValidator;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder.JwkSetUriReactiveJwtDecoderBuilder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.SupplierReactiveJwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtGrantedAuthoritiesConverterAdapter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

/**
 * Configures a {@link ReactiveJwtDecoder} when a JWK Set URI, OpenID Connect Issuer URI
 * or Public Key configuration is available. Also configures a
 * {@link SecurityWebFilterChain} if a {@link ReactiveJwtDecoder} bean is found.
 *
 * @author Madhura Bhave
 * @author Artsiom Yudovin
 * @author HaiTao Zhang
 * @author Anastasiia Losieva
 * @author Mushtaq Ahmed
 * @author Roman Golovin
 * @author Yan Kardziyaka
 */
@Configuration(proxyBeanMethods = false)
class ReactiveOAuth2ResourceServerJwkConfiguration {

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnMissingBean(ReactiveJwtDecoder.class)
	static class JwtConfiguration {

		private final OAuth2ResourceServerProperties.Jwt properties;

		private final List<OAuth2TokenValidator<Jwt>> additionalValidators;

		JwtConfiguration(OAuth2ResourceServerProperties properties,
				ObjectProvider<OAuth2TokenValidator<Jwt>> additionalValidators) {
			this.properties = properties.getJwt();
			this.additionalValidators = additionalValidators.orderedStream().toList();
		}

		@Bean
		@ConditionalOnProperty(name = "spring.security.oauth2.resourceserver.jwt.jwk-set-uri")
		ReactiveJwtDecoder jwtDecoder(ObjectProvider<JwkSetUriReactiveJwtDecoderBuilderCustomizer> customizers) {
			String jwkSetUri = this.properties.getJwkSetUri();
			Assert.state(jwkSetUri != null, "'jwkSetUri' must not be null");
			JwkSetUriReactiveJwtDecoderBuilder builder = NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri)
				.jwsAlgorithms(this::jwsAlgorithms);
			customizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
			NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = builder.build();
			String issuerUri = this.properties.getIssuerUri();
			List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
			if (issuerUri != null) {
				validators.add(new JwtIssuerValidator(issuerUri));
			}
			validators.addAll(getValidators());
			nimbusReactiveJwtDecoder.setJwtValidator(validators.isEmpty() ? JwtValidators.createDefault()
					: JwtValidators.createDefaultWithValidators(validators));
			return nimbusReactiveJwtDecoder;
		}

		private void jwsAlgorithms(Set<SignatureAlgorithm> signatureAlgorithms) {
			for (String algorithm : this.properties.getJwsAlgorithms()) {
				signatureAlgorithms.add(SignatureAlgorithm.from(algorithm));
			}
		}

		private List<OAuth2TokenValidator<Jwt>> getValidators() {
			List<String> audiences = this.properties.getAudiences();
			if (CollectionUtils.isEmpty(audiences) && this.additionalValidators.isEmpty()) {
				return Collections.emptyList();
			}
			List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
			if (!CollectionUtils.isEmpty(audiences)) {
				validators.add(audValidator(audiences));
			}
			validators.addAll(this.additionalValidators);
			return validators;
		}

		private JwtClaimValidator<List<String>> audValidator(List<String> audiences) {
			return new JwtClaimValidator<>(JwtClaimNames.AUD, (aud) -> nullSafeDisjoint(aud, audiences));
		}

		private boolean nullSafeDisjoint(@Nullable List<String> c1, List<String> c2) {
			return c1 != null && !Collections.disjoint(c1, c2);
		}

		@Bean
		@ConditionalOnPublicKeyJwtDecoder
		NimbusReactiveJwtDecoder jwtDecoderByPublicKeyValue() throws Exception {
			RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
				.generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey())));
			NimbusReactiveJwtDecoder jwtDecoder = NimbusReactiveJwtDecoder.withPublicKey(publicKey)
				.signatureAlgorithm(SignatureAlgorithm.from(exactlyOneAlgorithm()))
				.build();
			List<OAuth2TokenValidator<Jwt>> validators = getValidators();
			jwtDecoder.setJwtValidator(validators.isEmpty() ? JwtValidators.createDefault()
					: JwtValidators.createDefaultWithValidators(validators));
			return jwtDecoder;
		}

		private byte[] getKeySpec(String keyValue) {
			keyValue = keyValue.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
			return Base64.getMimeDecoder().decode(keyValue);
		}

		private String exactlyOneAlgorithm() {
			List<String> algorithms = this.properties.getJwsAlgorithms();
			int count = (algorithms != null) ? algorithms.size() : 0;
			if (count != 1) {
				throw new IllegalStateException(
						"Creating a JWT decoder using a public key requires exactly one JWS algorithm but " + count
								+ " were configured");
			}
			return algorithms.get(0);
		}

		@Bean
		@ConditionalOnIssuerLocationJwtDecoder
		SupplierReactiveJwtDecoder jwtDecoderByIssuerUri(
				ObjectProvider<JwkSetUriReactiveJwtDecoderBuilderCustomizer> customizers) {
			return new SupplierReactiveJwtDecoder(() -> {
				String issuerUri = this.properties.getIssuerUri();
				Assert.state(issuerUri != null, "'issuerUri' must not be null");
				JwkSetUriReactiveJwtDecoderBuilder builder = NimbusReactiveJwtDecoder.withIssuerLocation(issuerUri);
				customizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
				NimbusReactiveJwtDecoder jwtDecoder = builder.build();
				List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
				validators.add(new JwtIssuerValidator(issuerUri));
				validators.addAll(getValidators());
				jwtDecoder.setJwtValidator(JwtValidators.createDefaultWithValidators(validators));
				return jwtDecoder;
			});
		}

	}

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnMissingBean(ReactiveJwtAuthenticationConverter.class)
	@Conditional(JwtConverterPropertiesCondition.class)
	static class JwtConverterConfiguration {

		private final OAuth2ResourceServerProperties.Jwt properties;

		JwtConverterConfiguration(OAuth2ResourceServerProperties properties) {
			this.properties = properties.getJwt();
		}

		@Bean
		ReactiveJwtAuthenticationConverter reactiveJwtAuthenticationConverter() {
			JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
			PropertyMapper map = PropertyMapper.get();
			map.from(this.properties.getAuthorityPrefix()).to(grantedAuthoritiesConverter::setAuthorityPrefix);
			map.from(this.properties.getAuthoritiesClaimDelimiter())
				.to(grantedAuthoritiesConverter::setAuthoritiesClaimDelimiter);
			map.from(this.properties.getAuthoritiesClaimName())
				.to(grantedAuthoritiesConverter::setAuthoritiesClaimName);
			ReactiveJwtAuthenticationConverter jwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter();
			map.from(this.properties.getPrincipalClaimName()).to(jwtAuthenticationConverter::setPrincipalClaimName);
			jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(
					new ReactiveJwtGrantedAuthoritiesConverterAdapter(grantedAuthoritiesConverter));
			return jwtAuthenticationConverter;
		}

	}

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnMissingBean(SecurityWebFilterChain.class)
	static class WebSecurityConfiguration {

		@Bean
		@ConditionalOnBean(ReactiveJwtDecoder.class)
		SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, ReactiveJwtDecoder jwtDecoder) {
			http.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated());
			http.oauth2ResourceServer((server) -> customDecoder(server, jwtDecoder));
			return http.build();
		}

		private void customDecoder(OAuth2ResourceServerSpec server, ReactiveJwtDecoder decoder) {
			server.jwt((jwt) -> jwt.jwtDecoder(decoder));
		}

	}

	private static class JwtConverterPropertiesCondition extends AnyNestedCondition {

		JwtConverterPropertiesCondition() {
			super(ConfigurationPhase.REGISTER_BEAN);
		}

		@ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authority-prefix")
		static class OnAuthorityPrefix {

		}

		@ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.principal-claim-name")
		static class OnPrincipalClaimName {

		}

		@ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authorities-claim-name")
		static class OnAuthoritiesClaimName {

		}

	}

}
